package com.unicorn.service;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

/**
 * @author Meng Shen
 * @date 2022/5/10
 **/
@Component
public class GeoLiteService {

    public CityResponse getAddressByIp(String ip){
        DatabaseReader reader = null;
        CityResponse response = null;
        try{
            String path = ResourceUtils.getFile("classpath:GeoLite2-City.mmdb").getPath();
            File database = new File(path);
            // 读取数据库内容
            reader = new DatabaseReader.Builder(database).build();
            InetAddress ipAddress = InetAddress.getByName(ip);
            // 获取查询结果
            response = reader.city(ipAddress);
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }
        return response;
    }

}
